package zookeeper.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

public class ZKClient {
    private String connectString = "localhost:2181";
    private int sessionTimeout = 5000;

    private static ZooKeeper zooKeeper = null;

    private String parentNode = "/lin/index/test";



    public void createPath(String path) throws KeeperException, InterruptedException {
        Stat stat = zooKeeper.exists(path, false);
        if (stat == null) {
            zooKeeper.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("Created path: " + path);
        } else {
            System.out.println("Path already exists: " + path);
        }
    }

    public ZooKeeper intiClient() throws IOException, InterruptedException, KeeperException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, null);
        createPath(parentNode);
        return zooKeeper;
    }


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        // 获取连接
        ZKClient zkClient = new ZKClient();
        zooKeeper = zkClient.intiClient();
        zooKeeper.register(new ZkListener(zooKeeper));
    }


}
